package com.sczmgk.hotline.base;

import android.app.Activity;
import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline.dialog.DialogFactory;
import com.sczmgk.hotline.httpUtils.MyHttp;
import com.sczmgk.hotline.callback.CustomViewInterf;
import com.sczmgk.hotline.callback.MainHomeHandlerCallback;
import com.sczmgk.hotline.callback.OnRefreshListener;
import com.sczmgk.hotline.popup.PupDialog;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.MyToast;
import com.sczmgk.hotline.utils.Tools;
import com.sczmgk.hotline.view.MyHeadView;
import com.sczmgk.hotline.view.RefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 自定义主页Viewpager内容基类
 * 1.定义生命周期
 * 2.定义handler
 * 3.定义公用title
 */
public abstract class BaseView<T> implements CustomViewInterf {
    protected final int REFRESH_LIST = 101;
    protected final int HIDE_FOOTER_HEADER = 102;
    protected final String TAG = BaseView.this.getClass().getSimpleName();
    protected Dialog loadingDialog;
    protected Activity activity;
    /**
     * 自定义title
     */
    protected MyHeadView mHeadView;

    /**
     * 顶部广告与任务容器
     */
    protected View rootView;
    /**
     * 最外层的容器
     */
    protected FrameLayout container;
    protected Handler mHandler;
    protected boolean isResume;
    protected boolean isPause;
    protected boolean isStop;
    protected boolean isDestroy;
    protected boolean isCreate;

    /**
     * 默认第一次加载
     */
    protected final int LOAD_NORMAL = 0;
    /**
     * 下拉刷新状态
     */
    protected final int PULL_REFRESH = 1;
    /**
     * 上拉加载更多
     */
    protected final int LOAD_MORE = 2;

    /**
     * 已加载的页数
     */
    protected int loadedPage;
    /**
     * 当前页
     */
    protected int nowpage;
    /**
     * 总页数
     */
    protected int totalpages;

    protected List<T> lists = new ArrayList<>();

    protected String keyword = "";

    protected RefreshListView mListView;

    protected View mLayoutBottom;


    /**
     * 主页Handler消息回调
     */
    protected MainHomeHandlerCallback mainHomeHandlerCallback = new MainHomeHandlerCallback() {
        @Override
        public void onHandleMessage(Message msg) {
            mHandleMessage(msg);
            switch (msg.what) {

                case REFRESH_LIST:
                    if (mListView != null) {
                        mListView.hideHeaderView();
                        mListView.hideFooterView();
                    }
                    break;
                case HIDE_FOOTER_HEADER:
                    if (mListView != null) {
                        mListView.hideFooterView();
                        mListView.hideHeaderView();
                    }
                    if (mLayoutBottom != null) {
                        mLayoutBottom.setVisibility(View.VISIBLE);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public int currentItem;
    private PupDialog menuWindow;

    public void setCurrentItem(int currentItem) {
        this.currentItem = currentItem;
    }

    public void setListener() {
        mListView.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onPullDownRefresh() {
                MyLog.i(TAG, "下拉刷新----");
                pullDownRefresh();
            }

            @Override
            public void onLoadingMore() {
                MyLog.i(TAG, "totalpages:　" + totalpages + "      nowpages :" + nowpage);
                loadMore();
            }
        });
    }

    /**
     * 由子类实现
     *
     * @param msg
     */
    public abstract void mHandleMessage(Message msg);

    public BaseView(Activity context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        rootView = inflater.inflate(R.layout.layout_include_title, null);
        container = (FrameLayout) rootView.findViewById(R.id.main_home_container);
        mHeadView = (MyHeadView) rootView.findViewById(R.id.headview);
        mHeadView.setVisibility(View.GONE);
//        MainActivity activity = (MainActivity) context;
//        activity.setMainHomeHandlerCallback(mainHomeHandlerCallback );

    }

    /**
     * 取得实例化的View
     *
     * @return
     */
    public View getView() {
        return rootView;
    }

    /**
     * 初始化View
     */
    public abstract void initView();

    /**
     * 初始化头布局
     */

    public void initHeadView() {

    }

    /**
     * 显示title头
     */
    @Override
    public void visibleHeadView() {

        mHeadView.setVisibility(View.VISIBLE);
    }

    /**
     * 设置左边按钮显示状态
     *
     * @param enabled
     */
    @Override
    public void setLeftBtnEnabled(boolean enabled) {

    }

    /**
     * 设置左边按钮显示状态
     *
     * @param visible
     */
    @Override
    public void setLeftBtnVisibility(int visible) {

        mHeadView.setLeftBtnVisibility(visible);
    }

    public void setTitleIconText(int res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconText(String res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconClick(View.OnClickListener listener) {
        mHeadView.setTitleIconClick(listener);
    }

    public void setTitleIconVisiable(int visiable) {
        mHeadView.setTitleIconVisiable(visiable);
    }


    public void setNextRightBtnVisibility(int visible) {
        mHeadView.setNextRightBtnVisibility(visible);
    }

    public void setNextRightBtnBackground(int resource) {
        mHeadView.setNextRightBtnBackground(resource, -1);
    }

    public void setNextRightBtnClickListener(View.OnClickListener listener) {
        mHeadView.setNextRightBtnClickListener(listener);
    }

    /**
     * 设置左边按钮背景
     *
     * @param resource
     */
    @Override
    public void setLeftBtnBackground(int resource) {

        mHeadView.setLeftBtnBackground(resource);
    }

    /**
     * 设置左边按钮背景
     *
     * @param resource
     * @param text
     */
    @Override
    public void setLeftBtnBackground(int resource, int text) {

        mHeadView.setLeftBtnBackground(resource, text);
    }

    /**
     * 设置左边按钮背景
     *
     * @param resource
     * @param text
     * @param textColorResource
     */
    @Override
    public void setLeftBtnBackground(int resource, int text, int textColorResource) {

        mHeadView.setLeftBtnBackground(resource, text, textColorResource);
    }

    /**
     * 获取左边按钮的背景资源ID
     *
     * @param textColorResource
     */
    @Override
    public void setLeftBtnTextColor(int textColorResource) {

        mHeadView.setLeftBtnTextColor(textColorResource);
    }

    /**
     * 设置左边按钮的文字
     *
     * @param text
     */
    @Override
    public void setLeftBtnText(String text) {

        setLeftBtnText(text);
    }

    //TODO 分享按钮的点击事件
    public void setShareBtnClickListener(View.OnClickListener listener) {
        mHeadView.setShareBtnClickListener(listener);
    }

    //TODO 分享按钮的显示
    public void setShareBtnVisiable(int visible) {
        mHeadView.setShareBtnVisibility(visible);
    }

    //TODO 分享按钮的北京
    public void setShareBtnBGResource(int res) {
        mHeadView.setShareBtnBackground(res);
    }


    /**
     * 设置左边按钮背景 一旦为左边按钮设置监听，将会导致无法切换menu菜单
     *
     * @param listener
     */
    @Override
    public void setLeftBtnClickListener(View.OnClickListener listener) {

        mHeadView.setLeftBtnClickListener(listener);
    }

    /**
     * 设置左边按钮显示状态
     *
     * @param enabled
     */
    @Override
    public void setRightBtnEnabled(boolean enabled) {

        //未实现
    }

    /**
     * 设置右边按钮显示状态
     *
     * @param visible
     */
    @Override
    public void setRightBtnVisibility(int visible) {

        mHeadView.setRightBtnVisibility(visible);
    }


    /**
     * 设置右边按钮背景
     *
     * @param resource
     */
    @Override
    public void setRightBtnBackground(int resource) {

        mHeadView.setRightBtnBackground(resource);
    }

    /**
     * 设置右边按钮描述
     *
     * @param desc
     */
    @Override
    public void setRightBtnDescription(String desc) {

        mHeadView.setRightBtnDesc(desc);
    }

    /**
     * 设置右边按钮背景
     *
     * @param resource
     * @param text
     */
    @Override
    public void setRightBtnBackground(int resource, int text) {

        mHeadView.setRightBtnBackground(resource, text);
    }

    /**
     * 设置右边按钮背景
     *
     * @param resource
     * @param text
     * @param textColorResource
     */
    @Override
    public void setRightBtnBackground(int resource, int text, int textColorResource) {

        mHeadView.setRightBtnBackground(resource, text, textColorResource);
    }

    /**
     * 获取左边按钮的背景资源ID
     *
     * @param textColorResource
     */
    @Override
    public void setRightBtnTextColor(int textColorResource) {

        mHeadView.setRightBtnTextColor(textColorResource);
    }


    /**
     * 设置右边按钮的文字
     *
     * @param text
     */
    @Override
    public void setRigthBtnText(String text) {

    }

    /**
     * 设置右边按钮文字
     *
     * @param resid
     */
    @Override
    public void setRightBtnText(int resid) {

        mHeadView.setRightBtnText(resid);
    }


    public void setRightBtnText(String text) {

        mHeadView.setRightBtnText(text);
    }

    /**
     * 设置左边按钮背景 一旦为左边按钮设置监听，将会导致无法切换menu菜单
     *
     * @param listener
     */
    @Override
    public void setRightBtnClickListener(View.OnClickListener listener) {

        mHeadView.setRightBtnClickListener(listener);
    }

    /**
     * 设置标题icom
     *
     * @param resource
     */
    @Override
    public void setTitleIcon(int resource) {

        mHeadView.setTitleIcon(resource);
    }

    /**
     * 设置标题
     *
     * @param resource
     */
    @Override
    public void setTitle(int resource) {

        mHeadView.setTitle(resource);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    @Override
    public void setTitle(String title) {

        mHeadView.setTitle(title);
    }

    /**
     * 设置标题颜色
     *
     * @param color
     */
    @Override
    public void setTitleColor(int color) {

        mHeadView.setTitleColor(color);
    }

    /**
     * 设置头部背景
     *
     * @param color
     */
    @Override
    public void setHeadBackgroudColor(int color) {

        mHeadView.setHeadBackground(color);
    }

    /**
     * 设置标题栏显示状态
     *
     * @param visible
     */
    @Override
    public void setHeadViewVisibility(int visible) {

        mHeadView.setVisibility(visible);
    }

    /**
     * 显示底部弹出框
     * @param pupid    弹出框的 id
     * @param pupEvent 弹出框 按钮的监听事件接口
     */
    public void showPup(String pupid, PupDialog.PupEvent pupEvent) {
        dismissPup();
        menuWindow = new PupDialog(activity, pupid, pupEvent);
        // 显示窗口
        menuWindow.showAtLocation(getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void dismissPup() {
        if (null != menuWindow && menuWindow.isShowing()) {
            menuWindow.dismiss();
        }
    }

    public void onCreate() {

        isCreate = true;
        isPause = false;
        isDestroy = false;
        isResume = false;
        isStop = false;
    }


    public void onDestroy() {

        isDestroy = true;
        isPause = false;
        isCreate = false;
        isStop = false;
        isResume = false;
        if (loadingDialog != null) {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
                loadingDialog = null;
            }
        }
    }


    public void onPause() {

        isPause = true;
        isCreate = false;
        isResume = false;
        isStop = false;
        isDestroy = false;
        dismissLoadingDiaLog();

    }


    public void onResume() {

        isResume = true;
        isCreate = false;
        isPause = false;
        isStop = false;
        isDestroy = false;

    }


    public void onStop() {

        isStop = true;
        isCreate = false;
        isResume = false;
        isStop = false;
        isDestroy = false;

    }

    protected void pullDownRefresh() {
        initData(1, keyword, PULL_REFRESH);
    }

    protected void loadMore() {

        if (totalpages > nowpage) {
            initData(nowpage + 1, keyword, LOAD_MORE);
        } else {
            Message msg = Message.obtain();
            msg.what = HIDE_FOOTER_HEADER;
            mHandler.sendMessage(msg);
            MyToast.show(activity, "没有更多数据！");
        }
    }

    public void initData(final int page, String keyoword, final int loadStatus) {

        showLoadingDiaLog();
        if (mLayoutBottom != null){
            mLayoutBottom.setVisibility(View.GONE);
        }

        Map<String, Object> maps = getMaps(page,keyoword);
        MyHttp.request(activity, getUrl(), maps, MyHttp.POST, false, getCacheKey(), new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
              dismissLoadingDiaLog();
            }

            @Override
            public void onVerifySuccess(String dataRaw) {
              dismissLoadingDiaLog();
                try {
                    parseJson(dataRaw, loadStatus);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onServerUnKnownError() {
              dismissLoadingDiaLog();
            }

            @Override
            public void onErrorCodeError(String msg) {
                dismissLoadingDiaLog();
            }
        });
    }

    protected abstract Map<String,Object> getMaps(int page, String keyoword);

    protected abstract String getCacheKey();

    protected void parseJson(String dataRaw, int loadStatus) {
        if (Tools.isEmpty(dataRaw)) {
            MyLog.i("获取发现列表", "get find json error");
            return;
        }

        //这里要取得泛型的类型
        Class clazz = getJsonClazz();

        JSONArray datalist = null;
        List<T> datas = new ArrayList<>();
        try {
            //取到最外层字段
            JSONObject jsonObject = new JSONObject(dataRaw);
            nowpage = jsonObject.getInt("nowpage");
            totalpages = jsonObject.getInt("totalpages");

            try {
                int count = jsonObject.getInt("count");
            } catch (JSONException e) {
                e.printStackTrace();
                MyLog.e(TAG, "count，解析错误");
            }
            String systemtime = jsonObject.getString("systemtime");
            datalist = jsonObject.getJSONArray("datalist");
            // TODO 取出第二个list
            try {
                JSONArray extrasList = jsonObject.getJSONArray("accountants");
            } catch (JSONException e) {
                e.printStackTrace();
                MyLog.e(TAG, "exteasList，解析错误");
            }
            //取得数组大小
            int len = datalist.length();
            for (int i = 0; i < len; i++) {
                //分别取出对像
                String data = datalist.get(i).toString();
                Gson gson = new Gson();
                T m = (T) gson.fromJson(data, clazz);
                datas.add(m);
            }
            MyLog.d(TAG, "lists   size() : " + datas.size());
        } catch (JSONException e) {
            e.printStackTrace();
            MyLog.e(TAG, "公用List josn   解析错误");
        }

        if (this.nowpage > loadedPage) { //缓存已加载的页数
            loadedPage = this.nowpage;
        }

        if (loadStatus == PULL_REFRESH) { //下拉刷新，处理队列
            if (nowpage == 1) {//加载的当前页是第一页
                if (lists.size() > 0) {
                    MyLog.i(TAG, "初始化或下拉刷新的第一页，清空集合 ！");
                    lists.clear();
                }
            }
            lists.addAll(datas);
            refreshList();
        } else if (loadStatus == LOAD_MORE) { //加载更多，addall
            MyLog.i(TAG, "加载更多的第：" + nowpage + "  页");
            lists.addAll(datas);
            refreshList();
        } else {
            if (lists.size() > 0) {
                MyLog.i(TAG, "初始化或下拉刷新的第一页，清空集合 ！");
                lists.clear();
            }
            lists.addAll(datas);
            refreshList();
        }

    }

    /**
     * 发消息更新list
     */
    protected void refreshList() {
        Message msg = Message.obtain();
        msg.what = REFRESH_LIST;
        mHandler.sendMessage(msg);
    }

    /**
     * 取得泛型的类型的字节码
     *
     * @return
     */
    public Class getJsonClazz() {
        //1.取得当前运行的clss（传入M 的类）
        Class clazz = getClass();
        //2.取得父类的类型（也就是本类）
        Type superclass = clazz.getGenericSuperclass();
        //3.判断本类是否支持泛型
        if (superclass instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) superclass).getActualTypeArguments();
            //取得第一个就是实际类型
            Type actualTypeArgument = actualTypeArguments[0];
            //强转成字节码
            Class c = (Class) actualTypeArgument;
            //得到实例
            return c;
        }
        return null;
    }

    public void setLoadingDialog(Dialog loadingDialog) {
        this.loadingDialog = loadingDialog;
    }


    protected void showLoadingDiaLog(){
        DialogFactory.dismissLoadingDialog(activity,loadingDialog);
        if(loadingDialog == null){
            loadingDialog = DialogFactory.getLoadingDialog(activity, R.string.dialog_loading);
        }
        DialogFactory.showDialog(activity,loadingDialog);
    }
    protected void dismissLoadingDiaLog(){
        DialogFactory.dismissLoadingDialog(activity,loadingDialog);
    }
}
